<template>
  <div class="t-reserve-time">
    <div
      class="no-select"
      v-if="days.length"
    >
      <!--      <div>-->
      <!--        选中日期：{{ currentDate ? currentDate.format('YYYY年MM月DD日') : '' }}-->
      <!--      </div>-->
      <div class="flex flex-center flex-row">
        <el-icon
          class="cursor-pointer medium-font-size"
          @click="onPrev"
          v-if="isShowPrev()"
        >
          <ele-Back />
        </el-icon>
        <div class="title">
          {{ startDate.format("YYYY年MM月DD日") }} -
          {{ endDate.format("YYYY年MM月DD日") }}
        </div>
        <el-icon
          class="cursor-pointer medium-font-size"
          @click="onNext"
          v-if="isShowNext()"
        >
          <ele-Right />
        </el-icon>
      </div>
      <div>
        <dl class="flex flex-jc-center t-c">
          <dd
            v-for="item in days"
            class="flex-1"
            :key="item.day"
            @click="onClick(item.dayjs)"
            :class="[isDaySame(item.dayjs) ? 'active' : '', notDisabled(item.dayjs) ? '' : 'disabled']"
          >
            <p>{{ item.week }}</p>
            <p>{{ item.day }}</p>
          </dd>
        </dl>
        <div
          v-if="timeRangeList.length"
          class="time-range-list"
        >
          <el-row type="flex">
            <el-col
              class="time-range-item"
              :class="[currentTimeRange === tr.text ? 'active' : '', timeIsDisabled(tr) ? 'disabled' : '']"
              :span="3"
              :xs="5"
              :sm="4"
              :md="3"
              :lg="3"
              v-for="(tr, index) in timeRangeList"
              :key="tr.text"
              @click="onClickTimeRange(tr)"
            >
              <div>{{ tr.text }}</div>
              <div class="status">{{ tr.status }}</div>
            </el-col>
          </el-row>
        </div>
        <el-empty
          v-else
          :description="$t('formgen.reserveTimeRange.noPeriodOfTime')"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter.js";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore.js";
import { i18n } from "@/i18n";

dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);

const weeks = [
  i18n.global.t("formgen.reserveTimeRange.sunday2"),
  i18n.global.t("formgen.reserveTimeRange.monday"),
  i18n.global.t("formgen.reserveTimeRange.tuesday"),
  i18n.global.t("formgen.reserveTimeRange.wednesday"),
  i18n.global.t("formgen.reserveTimeRange.thursday"),
  i18n.global.t("formgen.reserveTimeRange.friday"),
  i18n.global.t("formgen.reserveTimeRange.saturday")
];

const props = defineProps({
  value: [Date, String, Number],
  // 日期范围
  dateRange: {
    type: Array,
    default: () => []
  },
  // 可以选择的天
  chosenDayOfWeek: {
    type: Array,
    default: () => []
  },
  // 时间范围
  timeRangeList: {
    type: Array,
    default: () => []
  },
  project: {
    type: Object,
    default: () => {}
  }
});

const emit = defineEmits(["changeDate", "update:value"]);

const currentTimeRange = ref("");
const currentDate = ref("");
const startDate = ref("");
const endDate = ref("");
const minDate = ref("");
const maxDate = ref("");
const days = ref([]);

watch(currentDate, val => {
  emit("changeDate", dayjs(val).format("YYYY-MM-DD"));
});

const getDayArr = s => {
  let e = s.add(6, "d");
  startDate.value = s;
  endDate.value = e;
  getDays(s);
};

const getDays = day => {
  let s = dayjs(day);
  let num = 7;
  let arr = [];
  let cur = "";
  for (let i = 0; i < num; i++) {
    let c = s.add(i, "day");
    if (!cur && notDisabled(c)) {
      cur = c;
    }
    let obj = {
      day: c.format("MM.DD"),
      week: weeks[c.get("day")],
      dayjs: c
    };
    arr.push(obj);
  }
  if (!currentDate.value) {
    currentDate.value = cur;
  }
  days.value = arr;
};

/**
 * 返回false表示禁用
 * @param d
 * @returns {*|boolean}
 */
const notDisabled = d => {
  // 是否禁用
  console.log(d);
  if (props.chosenDayOfWeek && props.chosenDayOfWeek.length) {
    const allowWeekDay = props.chosenDayOfWeek.includes(d.day());
    if (!allowWeekDay) {
      return false;
    }
  }
  // 是否在日期范围内
  if (minDate.value && maxDate.value) {
    return d.isSameOrBefore(maxDate.value, "D") && d.isSameOrAfter(minDate.value, "D");
  }
  return true;
};

const timeIsDisabled = t => {
  if (t.value !== null && t?.value <= 0) {
    return true;
  }
  let nowTime = new Date();
  let time = new Date(dayjs(currentDate.value).format("YYYY/MM/DD ") + t.text.split("-")[1] + ":00");
  return time < nowTime;
};

const onClick = d => {
  if (!notDisabled(d)) {
    return;
  }
  currentTimeRange.value = "";
  currentDate.value = d;
};

const isDaySame = d => {
  return d.isSame(currentDate.value, "d");
};

const onPrev = () => {
  let s = startDate.value.add(-7, "d");
  getDayArr(s);
};

const onNext = () => {
  let s = endDate.value.add(1, "d");
  getDayArr(s);
};

const onClickTimeRange = tr => {
  if (!notDisabled(currentDate.value)) {
    return;
  }
  if (timeIsDisabled(tr)) {
    return;
  }
  currentTimeRange.value = tr.text;
  emit("update:value", dayjs(currentDate.value).format("YYYY-MM-DD") + " " + currentTimeRange.value);
};

const isShowPrev = () => {
  if (minDate.value) {
    let d = days.value[0]?.dayjs;
    return !d.isSameOrBefore(minDate.value, "D");
  }
  return true;
};

const isShowNext = () => {
  if (maxDate.value) {
    return days.value[6]?.dayjs.isBefore(maxDate.value, "D");
  }
  return true;
};

onMounted(() => {
  // 加载默认值 显示时候使用
  if (props.value) {
    let arr = props.value.split(" ");
    currentDate.value = dayjs(arr[0]);
    currentTimeRange.value = arr[1];
    getDayArr(currentDate.value);
    return;
  } else {
    getDayArr(dayjs());
  }
  // 提前预约
  //是否开启提前预约
  if (props.project.reserveBeforeDay && props.project.reserveAfterDay) {
    const reserveBeforeDay = props.project.reserveBeforeDay;
    const reserveAfterDay = props.project.reserveAfterDay;
    minDate.value = dayjs().add(reserveBeforeDay, "day");
    maxDate.value = dayjs().add(reserveBeforeDay + reserveAfterDay - 1, "day");
    currentDate.value = minDate.value;
    return;
  }
  // 如果限制了日期范围
  if (props.dateRange && props.dateRange.length) {
    minDate.value = dayjs(props.dateRange[0]);
    maxDate.value = dayjs(props.dateRange[1]);
    // 如果最小日期大于当前日期 则使用最小日期
    if (dayjs().isSameOrBefore(minDate.value, "D")) {
      currentDate.value = minDate.value;
    }
  }
});
</script>

<style lang="scss" scoped>
.t-reserve-time {
  .flex {
    display: flex;
  }

  .flex-row {
    flex-direction: row;
  }

  .flex-row > * {
    display: block;
  }

  .flex-row-rev {
    flex-direction: row-reverse;
  }

  .flex-column {
    flex-wrap: wrap;
    flex-direction: column;
  }

  .flex-column-rev {
    flex-direction: column-reverse;
  }

  .flex-wrap {
    flex-wrap: wrap;
  }

  .flex-jc-center {
    justify-content: center;
  }

  .flex-jc-start {
    justify-content: flex-start;
  }

  .flex-jc-end {
    justify-content: flex-end;
  }

  .flex-jc-between {
    justify-content: space-between;
  }

  .flex-jc-around {
    justify-content: space-around;
  }

  .flex-ai-center {
    align-items: center;
  }

  .flex-ai-start {
    align-items: flex-start;
  }

  .flex-ai-end {
    align-items: flex-end;
  }

  .flex-ai-baseline {
    align-items: baseline;
  }

  .flex-ac-center {
    align-content: center;
  }

  .flex-ac-start {
    align-content: flex-start;
  }

  .flex-ac-end {
    align-content: flex-end;
  }

  .flex-ac-between {
    align-content: space-between;
  }

  .flex-ac-around {
    align-content: space-around;
  }

  .flex-center {
    justify-content: center;
    align-items: center;
  }

  .flex-1 {
    flex: 1;
    overflow: hidden;
  }

  .title {
    font-size: 14px;
    font-weight: bold;
    margin: 0 40px;
  }

  * {
    margin: 0;
    padding: 0;
  }

  .t-c {
    text-align: center;
    cursor: pointer;
  }

  dl {
    border-bottom: 1px solid #e6ebed;
    margin-top: 10px;
  }

  dd {
    padding-bottom: 5px;
    margin-bottom: -1px;
  }

  .active {
    color: var(--el-color-primary);
    border-bottom: 2px solid var(--el-color-primary);
  }

  .disabled {
    color: #999;
    cursor: none;
  }

  .no-select {
    user-select: none;
  }

  .time-range-list .el-row {
    flex-wrap: wrap;
  }

  .time-range-list .time-range-item {
    background-color: rgba(46, 200, 178, 0.03);
    border: 1px solid rgba(46, 200, 178, 0.4);
    height: 70px;
    text-align: center;
    vertical-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 5px;
    border-radius: 5px;
    cursor: pointer;
  }

  .time-range-item.disabled {
    border: var(--el-border);
    cursor: not-allowed;

    .status {
      color: var(--el-border-color);
    }

    &:hover {
      border: var(--el-border);
    }
  }

  .status {
    color: var(--el-color-primary);
  }

  .time-range-list .time-range-item:hover {
    border-color: var(--el-color-primary);
  }

  .time-range-list .time-range-item.active {
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary);
    color: #ffffff;

    .status {
      color: #ffffff;
    }
  }
}
</style>
